package com.siyuanren.gcocp.config;

import com.siyuanren.gcocp.common.config.PublicConfig;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.menu.WxMenu;
import me.chanjar.weixin.common.bean.menu.WxMenuButton;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.util.crypto.SHA1;
import me.chanjar.weixin.mp.api.WxMpConfigStorage;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.menu.WxMpGetSelfMenuInfoResult;
import me.chanjar.weixin.mp.bean.menu.WxMpMenu;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import me.chanjar.weixin.mp.bean.result.WxMpUserList;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author guwr
 * @date 2018/4/4
 */
public class MenuConfig {

    /**
     * 定义菜单结构
     *
     * @return
     */
    private static WxMenu getMenu(WxMpService wxMpService) throws Exception {

//        MainConfig mainConfig = new MainConfig("wx91cb107f6dd2f0ba", "177a542cde192062390ed64fb26cc328", "siyuanren", "fjxW0IUx2npm2SSvNXHO9xJfe5FKgxpbdusBmblR7p8");
//        WxMpService wxMpService = mainConfig.wxMpService();
        WxMenu menu = new WxMenu();
        WxMenuButton button1 = new WxMenuButton();
        button1.setType(WxConsts.MenuButtonType.VIEW);
        button1.setName("开始学习");
        button1.setAppId(PublicConfig.PUBLIC_WX_APPID);
        button1.setUrl("http://wx.gcocp.com/course/index");
//        button1.setUrl("https://wxf51bffd7272ef8ff.h5.xiaoe-tech.com");
//        button1.setUrl(PublicConfig.TOMCAT_URL + "/index");
//        button1.setUrl(wxMpService.oauth2buildAuthorizationUrl(PublicConfig.PUBLIC_WX_INDEX_URL, WxConsts.OAuth2Scope.SNSAPI_USERINFO, ""));
//
//        WxMenuButton button2 = new WxMenuButton();
//        button2.setName("我是卖家");
//
//        WxMenuButton button21 = new WxMenuButton();
//        button21.setType(WxConsts.MenuButtonType.VIEW);
//        button21.setName("我的订单");
//        button21.setUrl(wxMpService.oauth2buildAuthorizationUrl("", "snsapi_base", ""));
//
//        WxMenuButton button22 = new WxMenuButton();
//        button22.setType(WxConsts.MenuButtonType.VIEW);
//        button22.setName("收入统计");
//        button22.setUrl(wxMpService.oauth2buildAuthorizationUrl("", "snsapi_base", ""));
//
//        WxMenuButton button23 = new WxMenuButton();
//        button23.setType(WxConsts.MenuButtonType.VIEW);
//        button23.setName("发布商品");
//        button23.setUrl(wxMpService.oauth2buildAuthorizationUrl("", "snsapi_base", ""));
//
//        WxMenuButton button24 = new WxMenuButton();
//        button24.setType(WxConsts.MenuButtonType.VIEW);
//        button24.setName("商品管理");
//        button24.setUrl(wxMpService.oauth2buildAuthorizationUrl("", "snsapi_base", ""));
//
//        button2.getSubButtons().add(button21);
//        button2.getSubButtons().add(button22);
//        button2.getSubButtons().add(button23);
//        button2.getSubButtons().add(button24);

//		WxMenuButton button3 = new WxMenuButton();
//		button3.setType(MenuButtonType.CLICK);
//		button3.setName("使用帮助");
//		button3.setKey("help");

        menu.getButtons().add(button1);
//        menu.getButtons().add(button2);
//		menu.getButtons().add(button3);
        wxMpService.getMenuService().menuDelete();
        wxMpService.getMenuService().menuCreate(menu);
        return menu;
    }

    /**
     * 运行此main函数即可生成公众号自定义菜单，注意要修改MainConfig构造方法行代码的对应四个参数为实际值
     *
     * @param args
     */
    public static void main(String[] args) throws Exception {
        MainConfig mainConfig = new MainConfig(PublicConfig.PUBLIC_WX_APPID, PublicConfig.PUBLIC_WX_APPSECRET, PublicConfig.PUBLIC_WX_TOKEN, PublicConfig.PUBLIC_WX_AESKEY);
        WxMpService wxMpService = mainConfig.wxMpService();
//        WxJsapiSignature jsapiSignature = wxMpService.createJsapiSignature("http://wenren.gcocp.com/wx/index");
//        System.out.println("jsapiSignature = " + jsapiSignature);
//        getJsapiTicket(wxMpService);
//        genSignature(wxMpService);
//        menu(wxMpService);
//        testSendTemplateMsg(wxMpService);
//        menuGet(wxMpService);
        userInfo(wxMpService);
//        material(wxMpService);
//        getMenu(wxMpService);
    }

    /**
     * 素材
     *
     * @param wxMpService
     */
    private static void material(WxMpService wxMpService) throws Exception {
        //先上传
        WxMediaUploadResult result = wxMpService.getMaterialService().mediaUpload(WxConsts.KefuMsgType.IMAGE, new File("d://save.png"));
        String mediaId = result.getMediaId();
        WxMpKefuMessage reply = new WxMpKefuMessage();
        reply.setToUser("on0z5wtrZyLP_IfHAj4q3qVMHdRY");
        reply.setMsgType(WxConsts.KefuMsgType.IMAGE);
        reply.setMediaId(mediaId);
        //再发送
        wxMpService.getKefuService().sendKefuMessage(reply);
    }


    private static void userInfo(WxMpService wxMpService) throws Exception {
        WxMpUserList list = wxMpService.getUserService().userList(StringUtils.EMPTY);
        for (String s : list.getOpenids()) {
            WxMpUser wxMpUser = wxMpService.getUserService().userInfo(s);
            WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                    .toUser(s)
                    .templateId("EIJotT_VsjUeU8hQPW315D7C-uQtm1Gtffqp9QYmpW0")
//                    .url("https://st.h5.xiaoe-tech.com/st/0dODCxdFJ")
                    .build();
            templateMessage.addData(new WxMpTemplateData("first", "思源心课堂平台升级，已购买课程请在【我的】-【历史已购】查看，给您造成不便敬请谅解。", "#2a75ed"))
                    .addData(new WxMpTemplateData("keyword1", "如何查看已购课程", "#2a75ed"))
                    .addData(new WxMpTemplateData("keyword2", "平台升级", "#2a75ed"));
            String msgId = wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
            System.out.println(msgId);
        }
    }

    private static void menuGet(WxMpService wxMpService) throws Exception {
        WxMpMenu wxMpMenu = wxMpService.getMenuService().menuGet();
        System.out.println("wxMpMenu = " + wxMpMenu);
    }

    private static void menu(WxMpService wxMpService) throws Exception {
        WxMpGetSelfMenuInfoResult selfMenuInfo = wxMpService.getMenuService().getSelfMenuInfo();
        System.out.println("selfMenuInfo = " + selfMenuInfo);
        wxMpService.getMenuService().menuDelete();
        wxMpService.getMenuService().menuCreate(getMenu(wxMpService));
    }

    private static void getJsapiTicket(WxMpService wxMpService) throws Exception {
        String jsapiTicket = wxMpService.getJsapiTicket(true);
        System.out.println("jsapiTicket = " + jsapiTicket);
    }

    private static void testSendTemplateMsg(WxMpService wxMpService) throws WxErrorException {
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss.SSS");
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                .toUser("on0z5wtrZyLP_IfHAj4q3qVMHdRY")
                .templateId("8G6XEB8N5B0lIJDIffZJiary5h8xMU-VYJnFk4j8IWg")
                .url("http://www.baidu.com")
                .build();
        templateMessage.addData(new WxMpTemplateData("userName", dateFormat.format(new Date()), "#FF00FF"))
                .addData(new WxMpTemplateData("courseName", "courseName张", "#FF00FF"))
                .addData(new WxMpTemplateData("date", "date时间", "#FF00FF"))
                .addData(new WxMpTemplateData("remark", RandomStringUtils.randomAlphanumeric(100), "#FF00FF"));
        String msgId = wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
        System.out.println(msgId);
    }

    private static void genSignature(WxMpService wxMpService) throws Exception {
//        noncestr=Wm3WZYTPz0wzccnW
//        jsapi_ticket=sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg
//        timestamp=1414587457
//        url=http://mp.weixin.qq.com?params=value
//        https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx91cb107f6dd2f0ba&redirect_uri=http://wenren.gcocp.com/index.html&response_type=code&scope=snsapi_base&state=#wechat_redirect
//        String accessToken = wxMpService.getAccessToken();
        String jsapiTicket = wxMpService.getJsapiTicket(true);
        String str = "jsapi_ticket=" + jsapiTicket + "&noncestr=1&timestamp=1&url=http://wenren.gcocp.com/wx/index";
        System.out.println("str = " + str);
        String gen = SHA1.gen(str);
        System.out.println("gen = " + gen);
    }

    public static class MainConfig {
        private String appId;
        private String appSecret;
        private String token;
        private String aesKey;

        /**
         * 为了生成自定义菜单使用的构造函数
         *
         * @param appId
         * @param appSecret
         * @param token
         * @param aesKey
         */
        protected MainConfig(String appId, String appSecret, String token, String aesKey) {
            this.appId = appId;
            this.appSecret = appSecret;
            this.token = token;
            this.aesKey = aesKey;
        }

        public WxMpConfigStorage wxMpConfigStorage() {
            WxMpInMemoryConfigStorage configStorage = new WxMpInMemoryConfigStorage();
            configStorage.setAppId(this.appId);
            configStorage.setSecret(this.appSecret);
            configStorage.setToken(this.token);
            configStorage.setAesKey(this.aesKey);
            return configStorage;
        }

        public WxMpService wxMpService() {
            WxMpService wxMpService = new WxMpServiceImpl();
            wxMpService.setWxMpConfigStorage(wxMpConfigStorage());
            return wxMpService;
        }

    }
}
